class Solution {
    public int lastStoneWeightII(int[] stones) {
        int n=stones.length;
        int sum=0;
        for(int num:stones) sum+=num;


        int k=sum/2;
        boolean dp[]=new boolean[k+1];
        dp[0]=true;
        if(stones[0]<=k) dp[stones[0]]=true;
        int index=0;

        for(int j=1;j<n;j++)
            for(int i=k;i>=0;i--){

                if(i-stones[j]>=0) dp[i]=dp[i-stones[j]]||dp[i];

            }

        for(int i=k;i>=0;i--){
            if(dp[i]){
                index=i;
                break;
            }
        }

        return sum-index-index;
    }
}